import GameInfo from "../model/GameInfo";
import { BulletStatus } from "../model/Enums";

export default class MatterManager extends Laya.EventDispatcher {
    private Matter: any = Laya.Browser.window.Matter;   
    private Engine: any = this.Matter.Engine;
    private World: any = this.Matter.World;
    private engine: any;

    static _ins: MatterManager;

    public static get instance() {
        if (!MatterManager._ins) {
            MatterManager._ins = new MatterManager();
        }
        return MatterManager._ins;
    }

    constructor() {
        super();
        this.init();
    }

    public init(): void {
        this.engine = this.Engine.create({
            enableSleeping: true
        });
        this.engine.world.gravity.y = 0;
        this.Engine.run(this.engine);

        this.Matter.Events.on(this.engine, 'collisionStart', this.onCollisionStart.bind(this));
    }
    
    public onCollisionStart(event): void{
        let bodyA = event.pairs[0].bodyA
        let bodyB = event.pairs[0].bodyB
        if((bodyA.label=== 'ball' && bodyB.label === 'bullet') ||(bodyA.label=== 'bullet' && bodyB.label === 'ball')){
           bodyA.parentContainer.removeSelf();
           this.remveFromWord(bodyA);

           bodyB.parentContainer.removeSelf();
           this.remveFromWord(bodyB);

           GameInfo.instance.bulletStatus = BulletStatus.Disappeared;
        }    
    }

    public addToWorld(body: any): void{
       this.World.add(this.engine.world, body)
    }

    public produceBall(ballX: number, ballY: number, ballRadius: number){
        let ball = this.Matter.Bodies.circle(ballX, ballY, ballRadius, {
            isStatic: false,
            label: 'ball',
            friction: 0,
            frictionStatic: 0,
            frictionAir: 0.0,
            density: 0.8,
            restitution: 1.03
        });   
        return ball;
    }

    public produceRect(rectX: number, rectY: number, rectWidth: number, rectHeight: number){
        let rect = this.Matter.Bodies.rectangle(rectX, rectY, rectWidth, rectHeight, {
            isStatic: true,
        });   
        return rect;
    }

    // set 球的速度
    public setBallVec(body: any, x :number, y :number){
        this.Matter.Body.setVelocity(body, this.Matter.Vector.create(x, y));
    }

    // 描边
    public drawBodyBorder(container: Laya.Sprite, BodyVertices: any): void{
        let vertices = []; 
        let vertice: any;
        for(let i=0; i<BodyVertices.length; i++){
           vertices.push(BodyVertices[i].x);
           vertices.push(BodyVertices[i].y);
        }
        vertices.push(BodyVertices[0].x);
        vertices.push(BodyVertices[0].y);

        container.graphics.drawLines(0, 0, vertices, "#ff0000", 7);
    }

    //
    public remveFromWord(body: any): void{
        this.World.remove(this.engine.world, body);
    }
    
}